<template>
  <div>
    <section>
      <el-row>
        <el-col :span="2">
          <el-button v-permission="'/user/add'" @click="addDialogVisible = true" type="primary" :icon="Plus">
            新增
          </el-button>
        </el-col>
        <el-col :span="22">
          <el-form :model="searchData" :inline="true">
            <el-form-item>
              <el-input type="text" placeholder="用户名" v-model="searchData.username" clearable
                        style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-input type="text" placeholder="姓名" v-model="searchData.realName" clearable
                        style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="searchData.sex" style="width: 150px">
                <el-option v-for="one in formCfg.sexList" :key="one.sex" :label="one.sexName"
                           :value="one.sex"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="loadTable" type="primary">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </section>

    <!-- 表格   -->
    <section>
      <el-table :data="tableData.rows" stripe :border="true" style="width: 100%">
        <el-table-column prop="id" label="系统编号">
        </el-table-column>
        <el-table-column prop="username" label="用户名">
        </el-table-column>
        <el-table-column prop="realName" label="姓名">
        </el-table-column>
        <el-table-column label="性别">
          <template v-slot:default="scope">
            <span v-if="scope.row.sex === 'M'">男</span>
            <span v-if="scope.row.sex === 'F'">女</span>
          </template>
        </el-table-column>
        <el-table-column label="照片">
          <!-- preview-teleported避免预览的图片被表格遮挡 -->
          <template v-slot:default="scope">
            <el-image v-if="scope.row.avatarPath" style="width: 50px;height: 50px;"
                      :src="toAddressable(scope.row.avatarPath)" :preview-src-list="[toAddressable(scope.row.avatarPath)]"
                      :preview-teleported="true" fit="fill"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="角色">
          <template v-slot:default="scope">
            <span v-if="scope.row.roles && scope.row.roles.length > 0" v-for="role in scope.row.roles" :key="role.id">
              <el-tag type="primary"> {{ role.roleCnName }}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot:default="scope">
            <el-button v-permission="'/user/assignRole,/role/queryAll'" type="warning" :icon="Delete"
                       @click="openRoleDia(scope.row)">分配角色
            </el-button>
            <el-button v-permission="'/user/queryById,/user/modifyById,/storage/uploadFile'" type="primary" :icon="Edit"
                       @click="openUpdateDia(scope.row.id)">编辑
            </el-button>
            <el-button v-permission="'/user/deleteById'" type="danger" :icon="Delete"
                       @click="deleteById(scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
    <!-- 分页   -->
    <section>
      <el-pagination @size-change="handlePageSizeChange" @current-change="handlePageNowChange"
                     :current-page="searchData.pageNow" :page-sizes="[5, 10, 15, 20]" :page-size="searchData.pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
      </el-pagination>
    </section>

    <!-- 新增对话框 -->
    <AddUser :addDialogVisible="addDialogVisible"
             @closeDialog="addDialogVisible = false"
             @addSuccess="handleAddSuccess"></AddUser>
    <!-- 修改对话框 -->
    <UpdateUser
        :updateDialogVisible="updateDialogVisible"
        @closeDialog="updateDialogVisible = false"
        @updateSuccess="handleUpdateSuccess" :idToUpdate="idToUpdate"></UpdateUser>
    <!-- 分配角色对话框 -->
    <RoleToAssign
        :roleToAssignDialogVisible="roleToAssignDialogVisible"
        @closeDialog="roleToAssignDialogVisible = false"
        :roleIds="currentUserRoleIds"
        :idToAssign="idToAssign"
        @confirmCheck="confirmCheck"></RoleToAssign>
  </div>
</template>
<script setup name='UserManage' lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import AddUser from '@/views/user/AddUser.vue';
import UpdateUser from '@/views/user/UpdateUser.vue';
import RoleToAssign from '@/views/user/RoleToAssign.vue'
import { useTable } from '@/hooks/useTable';
import { useResource } from '@/hooks/useResource';
import { loadTableApi, deleteByIdApi, assignRoleApi } from '@/api/userApi';
import type { AnyObjDefine } from '@/types/common.d.ts';
import { ElMessage } from 'element-plus';
// 对话框是否显示
let addDialogVisible = ref(false)
let updateDialogVisible = ref(false)
let roleToAssignDialogVisible = ref(false)
let idToUpdate = ref('')
let idToAssign = ref('')
let currentUserRoleIds = ref<string[]>([])

// 查询参数
let searchFormData = reactive({
  username: '',
  realName: '',
  sex: '',
})

let formCfg = reactive({
  sexList:[
    {sex:'',sexName:"全部"},
    {sex:'M',sexName:"男"},
    {sex:'F',sexName:"女"},
  ]
})

let {
  searchData,
  tableData,
  loadTable,
  handlePageSizeChange,
  handlePageNowChange,
  deleteById
} = useTable({ searchFormData, loadTableApi, deleteByIdApi })

let {toAddressable} = useResource()

// 打开分配角色对话框
function openRoleDia(user:AnyObjDefine) {
  idToAssign.value = user.id
  currentUserRoleIds.value = user.roles && user.roles.map((role:AnyObjDefine) =>  role.id)
  roleToAssignDialogVisible.value = true
}
// 打开修改对话框
function openUpdateDia(id: string) {
  idToUpdate.value = id
  updateDialogVisible.value = true
}
// 处理添加成功
function handleAddSuccess(){
  addDialogVisible.value = false
  loadTable()
}
// 处理更新成功
function handleUpdateSuccess(){
  updateDialogVisible.value = false
  loadTable()
}
// 处理确认分配角色
function confirmCheck(checkedRoleIds:string[]) {
  roleToAssignDialogVisible.value = false
  // 更新用户的角色
  assignRoleApi({userId:idToAssign.value,roleIds:checkedRoleIds})
      .then(result => {
        ElMessage({message:result.data,type:"success"})
        // 成功后刷新表格
        loadTable()
      })
}
onMounted(() => {
  loadTable()
})
</script>
<style scoped>
.el-tag {
  margin: 5px;
}
</style>